"""
研究助理配置设置
专门用于研究助理功能的配置，与业务配置分离
"""

from typing import Optional
import os
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import Field, model_validator
from dotenv import load_dotenv

load_dotenv()

class ResearchSettings(BaseSettings):
    """研究助理配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="RESEARCH_"
    )
    
    # OpenAI配置
    OPENAI_API_BASE: Optional[str] = Field(
        default=os.getenv("RESEARCH_OPENAI_API_BASE", ""),
        description="OpenAI API BASE URL"
    )
    OPENAI_API_KEY: str = Field(
        default=os.getenv("RESEARCH_OPENAI_API_KEY", ""),
        description="OpenAI API密钥（必须通过环境变量设置）"
    )
    OPENAI_MODEL: str = Field(
        default=os.getenv("RESEARCH_OPENAI_MODEL", ""),
        description="OpenAI模型名称"
    )
    OPENAI_MAX_TOKENS: int = Field(
        default=1000,  # 增加默认令牌数以提高兼容性
        description="OpenAI最大令牌数",
        ge=1,
        le=10000
    )
    OPENAI_TEMPERATURE: float = Field(
        default=0.7,
        description="OpenAI温度参数",
        ge=0.0,
        le=1.0
    )
    
    # 搜索配置
    SEARCH_MAX_RESULTS: int = Field(
        default=10,
        description="最大搜索结果数量",
        ge=1,
        le=50
    )
    SEARCH_TIMEOUT: int = Field(
        default=30,
        description="搜索超时时间(秒)",
        ge=1,
        le=300
    )
    
    # 工作流配置
    WORKFLOW_MAX_ITERATIONS: int = Field(
        default=20,
        description="工作流最大迭代次数",
        ge=1,
        le=50
    )
    WORKFLOW_TIMEOUT: int = Field(
        default=1200,
        description="工作流超时时间(秒)",
        ge=10,
        le=7200
    )
    
    # 缓存配置
    CACHE_ENABLED: bool = Field(
        default=True,
        description="是否启用缓存"
    )
    CACHE_TTL: int = Field(
        default=3600,
        description="缓存生存时间(秒)",
        ge=1,
        le=86400
    )
    
    # 多代理配置
    MULTI_AGENT_ENABLED: bool = Field(
        default=True,
        description="是否启用多代理模式"
    )
    AGENT_COORDINATION_TIMEOUT: int = Field(
        default=60,
        description="代理协调超时时间(秒)",
        ge=1,
        le=300
    )
    
    # 搜索服务器配置
    SEARCH_SERVER_TIMEOUT: int = Field(
        default=30,
        description="搜索服务器超时时间(秒)",
        ge=5,
        le=120
    )
    
    # Transformers离线模式
    TRANSFORMERS_OFFLINE: bool = Field(
        default=False,
        description="Transformers库是否在离线模式下运行"
    )
    
    # 日志配置
    LOG_LEVEL: str = Field(
        default="INFO",
        description="日志级别"
    )
    
    @model_validator(mode='after')
    def validate_research_settings(self) -> 'ResearchSettings':
        """验证研究配置"""
        valid_log_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
        if self.LOG_LEVEL not in valid_log_levels:
            raise ValueError(f"LOG_LEVEL必须是以下值之一: {valid_log_levels}")
        
        if not self.OPENAI_API_KEY:
            raise ValueError("RESEARCH_OPENAI_API_KEY不能为空，请在.env文件中设置")
        if not self.OPENAI_API_KEY.startswith("sk-"):
            raise ValueError("OPENAI_API_KEY格式不正确，应以'sk-'开头")
        
        if self.OPENAI_API_BASE and not self.OPENAI_API_BASE.startswith(('http://', 'https://')):
            raise ValueError("OPENAI_API_BASE必须以http://或https://开头")
        
        if self.WORKFLOW_TIMEOUT < self.SEARCH_TIMEOUT:
            raise ValueError("工作流超时时间应大于搜索超时时间")
        
        return self
    
    def is_simulation_mode(self) -> bool:
        """
        判断是否启用模拟模式
        
        Returns:
            bool: 如果启用模拟模式返回True，否则返回False
        """
        # 如果API密钥为空或为默认值，使用模拟模式
        if not self.OPENAI_API_KEY or self.OPENAI_API_KEY.strip() == "":
            return True
        
        # 检查环境变量是否启用模拟模式
        import os
        simulation_mode_enabled = os.getenv('SIMULATION_MODE_ENABLED', 'False').lower() == 'true'
        research_simulation_mode_enabled = os.getenv('RESEARCH_SIMULATION_MODE_ENABLED', 'False').lower() == 'true'
        
        return simulation_mode_enabled or research_simulation_mode_enabled
    

# 全局研究配置实例
research_settings = ResearchSettings()


def get_research_settings() -> ResearchSettings:
    """获取研究配置实例"""
    return research_settings
